package com.shcz.migu.ui.base;

import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;


import com.shcz.migu.R;
import com.shcz.migu.local_setting.LocalConstants;
import com.shcz.migu.presenter.base.BasePresenter;
import com.shcz.migu.presenter.base.BaseView;
import com.shcz.migu.ui.fragment.FailureFragment;
import com.shcz.migu.ui.fragment.LoadFragment;
import com.shcz.migu.utils.CommonToast;
import com.shcz.migu.utils.CommonUtils;
import com.shcz.migu.utils.ConvertDipPx;
import com.shcz.migu.widget.base.AutoHeightLayout;
import com.shcz.migu.widget.base.CTitleBar;

import butterknife.ButterKnife;


public abstract class BaseFragment<P extends BasePresenter> extends Fragment implements OnClickListener, BaseView {

    protected String TAG = this.getClass().getSimpleName();

    protected CTitleBar mTitleBar;
    private Fragment loadFragment, failureFragment;
    protected RelativeLayout contentView;
    protected View mainView;
    protected AutoHeightLayout autoHeightView;
    protected View mTopView;
    protected PopupWindow mPopupWindow;
    protected int TitleLeftType = 0;

    protected P mPresenter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView");
        mainView = inflater.inflate(R.layout.activity_base, container, false);
        initBaseViews();
        setupViews(inflater);
        ButterKnife.bind(this, mainView);
        mPresenter = createPresenter();
        initView();
        return mainView;
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        Log.d(TAG, "onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroy();
        }
        mPresenter = null;
        Log.d(TAG, "onDestroy");
    }

    protected abstract void setupViews(LayoutInflater inflater);

    protected abstract void initView();

    private void initBaseViews() {
        autoHeightView = (AutoHeightLayout) mainView.findViewById(R.id.auto_height_layout);
        mTitleBar = (CTitleBar) mainView.findViewById(R.id.c_titlebar);
        contentView = (RelativeLayout) mainView.findViewById(R.id.re_basecontent);
    }

    protected P createPresenter() {
        return null;
    }


    /**
     * 设置顶部固定view，和ContentView平级，注意每个Activity只能初始化一次
     *
     * @param layoutId layoutId
     */
    protected void setTopView(int layoutId) {
        ViewStub topViewStub = (ViewStub) mainView.findViewById(R.id.top_view);
        topViewStub.setLayoutResource(layoutId);
        topViewStub.inflate();

        mTopView = mainView.findViewById(R.id.top_view_id);
    }

    public void setContentView(LayoutInflater inflater, int layoutId) {
        contentView.removeAllViews();
        inflater.inflate(layoutId, contentView, true);
        mainView.findViewById(R.id.main_view).setBackgroundColor(CommonUtils.getColorById(R.color.transparent));
    }

    public void setContentView(View view) {
        contentView.removeAllViews();
        contentView.addView(view, new ViewGroup.LayoutParams(-1, -1));
    }

    public void setTitle(int stringid) {
        setTitle(getString(stringid));
    }

    public void setTitle(String string) {
        if (string != null) mTitleBar.setTitle(string);
    }

    public void setTitle(int stringid, int color) {
        setTitle(getString(stringid), getResources().getColor(color));
    }

    public void setTitle(String string, int color) {
        setTitle(string);
        mTitleBar.setTitleTextColor(color);
    }

    public void setTitleLeftImgButtonVisible(int visibility) {
        mTitleBar.setTitleLeftButtonVisibility(visibility);
    }

    public void setTitleLeftButton(int resId, OnClickListener listener) {
        mTitleBar.setTitleLeftButton(resId, listener);
    }

    protected void setNoTitle() {
        mTitleBar.setVisibility(View.GONE);
    }


    /**
     * View的状态
     */
    protected final static int View_State_Loadding = 0;
    protected final static int View_State_Normal = 1;
    protected final static int View_State_Fail = 2;
    protected final static int View_State_Empty = 3;
    protected final static int View_State_GONE = 4;

    protected void setViewState(int state) {
        switch (state) {
            case View_State_Loadding:
                setStateLoad();
                break;
            case View_State_Normal:
                setStateNormal();
                break;
            case View_State_Fail:
            case View_State_Empty:
                setStateFailOrEmpty();
                break;

            default:
                break;
        }
    }

    /**
     * 设置界面为Loadding
     */
    protected void setStateLoad() {
        if (loadFragment == null) {
            loadFragment = new LoadFragment();
        }
        if (!loadFragment.isAdded())
            setFragment(loadFragment);
    }

    /**
     * 设置界面为失败或者空，使用默认的icon和content，没有Button
     */
    protected void setStateFailOrEmpty() {
        if (failureFragment == null) {
            failureFragment = new FailureFragment();
        }
        setFragment(failureFragment);
    }

    /**
     * 设置界面为失败或者空 默认图片：iconResId == 0，图片空：iconResId == -1；
     *
     * @param iconResId    icon
     * @param contentResId content string id
     * @param btnResId     btn string id
     */
    protected void setStateFailOrEmpty(int iconResId, int contentResId, int btnResId) {
        setStateFailOrEmpty(iconResId, getString(contentResId), btnResId);
    }


    /**
     * 设置界面为失败或者空 默认图片：iconResId == 0，图片空：iconResId == -1；
     *
     * @param iconResId icon
     * @param content   string
     */
    protected void setStateFailOrEmpty(int iconResId, String content, int btnResId) {
        if (failureFragment == null) {
            failureFragment = new FailureFragment();
        }

        if (!failureFragment.isAdded()) {
            Bundle bundle = new Bundle();
            bundle.putInt(FailureFragment.ARGUMENT_ICON_ID, iconResId);
            bundle.putString(FailureFragment.ARGUMENT_CONTENT, content);
            bundle.putInt(FailureFragment.ARGUMENT_BUTTON, btnResId);
            failureFragment.setArguments(bundle);

            setFragment(failureFragment);
        }
    }

    /**
     * 设置界面为正常，会隐藏Loadding，应该在Load之后调用
     */
    protected void setStateNormal() {
        if (loadFragment != null) {
            removeFragment(loadFragment);
        }

        if (failureFragment != null) {
            removeFragment(failureFragment);
        }
    }

    /**
     * 设置Fragment，显示在Content中
     *
     * @param fragment fragment
     */
    protected void setFragment(Fragment fragment) {
        if (getActivity() != null && !getActivity().isFinishing()) {
            FragmentManager fm = getChildFragmentManager();
            FragmentTransaction transaction = fm.beginTransaction();
            transaction.replace(R.id.re_basecontent, fragment);
            transaction.commitAllowingStateLoss();
        }
    }

    /**
     * 去除Fragment显示
     *
     * @param fragment fragment
     */
    protected void removeFragment(Fragment fragment) {
        if (getActivity() != null && !getActivity().isFinishing()) {
            FragmentManager fm = getChildFragmentManager();
            FragmentTransaction transaction = fm.beginTransaction();
            transaction.remove(fragment);
            transaction.commitAllowingStateLoss();
        }
    }

    protected void setViewEmpty(int iconResId, int textResId, int btnResId) {
        setStateFailOrEmpty(iconResId, textResId, btnResId);
    }

    public Drawable getDrawable(int resid) {
        return getResources().getDrawable(resid);
    }

    public int dip2px(float dip) {
        return ConvertDipPx.dip2px(CommonUtils.getAppContext(), dip);
    }

    public boolean isEmpty(String str) {
        return CommonUtils.isEmpty(str);
    }

    @Override
    public void onClick(View v) {
    }

    protected void showToast(String msg) {
        CommonToast.showToast(msg);
    }


    @Override
    public void showNetWorkError() {
        CommonToast.showToast(getString(R.string.network_failed));
    }

    @Override
    public void showErrorMessage(String message) {
        if (message.contains(LocalConstants.NETWORK_FLAG)) {
            setViewState(View_State_Fail);
            CommonToast.showToast(R.string.net_work_error_msg);
        } else
            CommonToast.showToast(message);
    }

    @Override
    public void showLoadingView() {
        setViewState(View_State_Loadding);
    }

    @Override
    public void hideLoadingView() {
        setViewState(View_State_Normal);
    }

    @Override
    public void showEmptyView(int iconResId, int contentResId, int btnResId) {
        setStateFailOrEmpty(iconResId, contentResId, btnResId);
    }

    @Override
    public void showLoadingDialog(String msg) {
        showLoading(msg);
    }

    @Override
    public void hideLoadingDialog() {
        dismissLoading();
    }

    protected ProgressDialog mLoadingDialog;

    protected void showLoading(String msg) {
        if (mLoadingDialog == null) {
            mLoadingDialog = new ProgressDialog(getActivity());
            mLoadingDialog.setIndeterminate(true);
        }
        if (TextUtils.isEmpty(msg))
            mLoadingDialog.setMessage(getString(R.string.loading));
        else
            mLoadingDialog.setMessage(msg);
        mLoadingDialog.show();
    }

    protected void dismissLoading() {
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }


}
